//
//  NewspaperSingleArticleViewController.m
//  JianChaRiBao
//
//  Created by 常兴宇 on 13-10-31.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "NewspaperSingleArticleViewController.h"

@interface NewspaperSingleArticleViewController ()
{
    BOOL showTool;
    BOOL isShowStatusBar;
}

@end

@implementation NewspaperSingleArticleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        shouldSwipeBack = YES;
    }
    return self;
}
- (IBAction)backButtonClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#define IMAGEHIGHT self.view.bounds.size.height

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    NSLog(@"baseInfo:%@",self.baseInfo);
    showTool = YES;
    titleLabel.scrollType = ScrollSingle;
    titleLabel.font = [UIFont systemFontOfSize:21.0f];
    if (self.isDynamics) {
        titleLabel.textAlignment = UITextAlignmentCenter;
        titleLabel.text = [NSString stringWithFormat:@"动态 - %@",[self.baseInfo objectForKey:@"class_name"]];
    }else{
        titleLabel.text = [NSString stringWithFormat:@"中国保险报%@",self.titleStr];
        [titleLabel startScroll];
    }
    
    
    NSURL * url = [[NSBundle mainBundle] URLForResource:@"ArticleHTML/article" withExtension:@"html"];
    [mArticleWebView loadRequest:[NSURLRequest requestWithURL:url]];
    mArticleWebView.scrollView.delegate = self;
    contentOffSet = mArticleWebView.scrollView.contentOffset.y;

    [self createBottomView];
    [self createCurrView];
    [self getData];
}

-(void)getData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = nil;
        if (self.isDynamics) {
            obj = [[DataRequest sharedRequest] getDynamicsSingleArticle:[self.baseInfo objectForKey:@"public_opinion_id"]];
        }else{
            obj = [[DataRequest sharedRequest] getNewspaperSingleArticle:[self.baseInfo objectForKey:@"page_id"]];
        }
        NSLog(@"obj:%@",obj);
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([obj isKindOfClass:[NSString class]]) {
                self.jsonStr = obj;
                [self upDateDisplay];
            }
        });
    });

}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [self upDateDisplay];
}

-(void)upDateDisplay{
    if (self.jsonStr && !mArticleWebView.loading) {
        [mArticleWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"loadNewspaperData(%@);",self.jsonStr]];
    }
    

    NSInteger themeState = [[NSUserDefaults standardUserDefaults] integerForKey:@"themeState"];
    [mArticleWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeTheme(%d)",themeState - 103]];
    
    NSInteger fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"fontState"];
    [mArticleWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeFontSize(%d)",fontSize - 100]];
    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [UIView animateWithDuration:0.3 animations:^{
        bottomView.frame = CGRectMake(0, IMAGEHIGHT, 320, 60);
    }];
    
    
    if (scrollView == mArticleWebView.scrollView) {
        if (scrollView.contentOffset.y + mArticleWebView.bounds.size.height <= mArticleWebView.scrollView.contentSize.height && scrollView.contentOffset.y > 0) {
            contentOffSet = scrollView.contentOffset.y;
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.dragging == NO){
        return;
    }
    if (scrollView == mArticleWebView.scrollView && scrollView.contentSize.height > mArticleWebView.bounds.size.height) {
        if (scrollView.contentOffset.y >= contentOffSet && scrollView.contentOffset.y != 0) {
            if (showTool) {
                [self hideOptionBar];
            }
        }else{
            if (!showTool) {
                [self showOptionBar];
            }
        }
    }
    
}

-(void)createCurrView{
    currView = [[UIView alloc]initWithFrame:CGRectMake(0, IMAGEHIGHT - 40, 320, 40)];
    currView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    currView.userInteractionEnabled = YES;
    [self.view addSubview:currView];
    UIImageView * currImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    currImage.image = [UIImage imageNamed:@"tab_bg.png"];
    [currView addSubview:currImage];
    //    NSArray * array = [NSArray arrayWithObjects:@"分享",@"收藏",@"评论",@"设置" ,nil];
    NSArray * array = [NSArray arrayWithObjects:@"设置" ,nil];
    

    UISegmentedControl * seg = [[UISegmentedControl alloc]initWithItems:array];
    seg.frame = CGRectMake(20, 5, 280, 30);
    seg.segmentedControlStyle = UISegmentedControlStyleBordered;
    seg.momentary = YES;
    [seg addTarget:self action:@selector(segClicked:) forControlEvents:UIControlEventValueChanged];
    seg.tintColor = [UIColor whiteColor];
    [currView addSubview:seg];
    [currImage release];
    [seg release];
}
-(void)segClicked:(UISegmentedControl *)seg{
    if (mArticleWebView.scrollView.dragging) {
        return;
    }
    
    switch (seg.selectedSegmentIndex) {
        case 0:
        {
            [UIView animateWithDuration:0.3 animations:^{
                currView.frame = CGRectMake(0, IMAGEHIGHT, 320, 40);
                bottomView.frame = CGRectMake(0, IMAGEHIGHT - 60, 320, 60);
            }];
            
        }
            break;
        case 1:
        {
            
        }
            break;
        case 2:
        {
        }
            break;
        case 3:
        {
        }
            break;
            
        default:
            break;
    }
}

-(void)createBottomView{
    bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, IMAGEHIGHT, 320, 60)];
    bottomView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin ;
    bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomView];
    
    UIView * alphView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    alphView.backgroundColor = [UIColor blackColor];
    alphView.alpha = 0.4;
    [bottomView addSubview:alphView];
    [alphView release];
    
    fontView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    [bottomView addSubview:fontView];
    
    stateView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, 320, 30)];
    [bottomView addSubview:stateView];
    
    
    for (int i = 0 ; i < 3; i ++) {
        UIButton * button = [self createButtonWithFrame:CGRectMake(70 + i * 60, 2, 60, 25) tag:101 + i image:[UIImage imageNamed:[NSString stringWithFormat:@"font%d_bg.png",i + 1]] highlightImage:[UIImage imageNamed:[NSString stringWithFormat:@"font%d_bg_selected.png",i + 1]] action:@selector(topBtnClicked:)];
        [fontView addSubview:button];
    }
    //白天 夜间  牛皮纸 护眼
    NSArray * nameArray = [NSArray arrayWithObjects:@"白天",@"夜间",@"护眼",@"牛皮纸", nil];
    NSArray * imageArray = [NSArray arrayWithObjects:@"style_day.png",@"style_dark.png",@"style_old.png",@"style_hy.png", nil];
    NSArray * selectArray = [NSArray arrayWithObjects:@"style_day_selected.png",@"style_dark_selected.png",@"style_old_selected.png",@"style_hy_selected.png", nil];
    for (int i = 0; i < 4; i ++) {
        UIButton * button = [self createButtonWithFrame:CGRectMake(30 + 65 * i, 0, 65, 30) tag:104 + i image:[UIImage imageNamed:[imageArray objectAtIndex:i]] highlightImage:[UIImage imageNamed:[selectArray objectAtIndex:i]] action:@selector(bottomBtnClicked:)];
        [button setTitle:[nameArray objectAtIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [stateView addSubview:button];
    }
    NSInteger fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"fontState"];
    NSInteger themeState = [[NSUserDefaults standardUserDefaults] integerForKey:@"themeState"];
    if (fontSize != 0) {
        UIButton * fontBtn = (UIButton *)[self.view viewWithTag:fontSize];
        fontBtn.selected = YES;

    }
    if (themeState != 0) {
        UIButton * themeBtn = (UIButton *)[self.view viewWithTag:themeState];
        themeBtn.selected = YES;
    }
}
-(UIButton *)createButtonWithFrame:(CGRect)frame tag:(NSInteger)tag image:(UIImage *)image highlightImage:(UIImage *)highlightImage action:(SEL)action{
    UIButton * mButton = [UIButton buttonWithType:UIButtonTypeCustom];
    mButton.frame = frame;
    mButton.tag = tag;
    [mButton setBackgroundImage: image forState:UIControlStateNormal];
    [mButton setBackgroundImage: highlightImage forState:UIControlStateHighlighted];
    [mButton setBackgroundImage:highlightImage forState:UIControlStateSelected];
    [mButton addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return mButton;
}
-(void)bottomBtnClicked:(UIButton *)button{
    for (UIButton * btn in stateView.subviews) {
        if (button == btn) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
//    [self changeColorWithTag:button.tag];
    [[NSUserDefaults standardUserDefaults] setInteger:button.tag forKey:@"themeState"];
    [mArticleWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeTheme(%d)",button.tag - 103]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


-(void)topBtnClicked:(UIButton *)button{
    for (UIButton * btn in fontView.subviews) {
        if (button == btn) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    [[NSUserDefaults standardUserDefaults] setInteger:button.tag forKey:@"fontState"];
    [mArticleWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeFontSize(%d)",button.tag - 100]];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

-(void)showOptionBar{
    showTool = YES;
    isShowStatusBar = NO;
    [UIView animateWithDuration:0.2 animations:^{
        topView.frame = CGRectMake(0, 0, 320, 60);
        mArticleWebView.frame = CGRectMake(0, 60, 320, IMAGEHIGHT - 60);
        currView.frame = CGRectMake(0, IMAGEHIGHT - 40, 320, 40);
    }];
    
    if ([UIDevice currentDevice].systemVersion.floatValue<7.0) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    }else{
        [self hiddenStatus];
    }
    
    NSLog(@"showOptionBar");
}
-(void)hideOptionBar{
    showTool = NO;
    isShowStatusBar = YES;
    [UIView animateWithDuration:0.2 animations:^{
        
        topView.frame = CGRectMake(0, -60, 320, 60);
        mArticleWebView.frame = CGRectMake(0, 0, 320, IMAGEHIGHT);
        currView.frame = CGRectMake(0, IMAGEHIGHT, 320, 40);
    }];
    
    if ([UIDevice currentDevice].systemVersion.floatValue<7.0) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    }else{
        [self hiddenStatus];
    }

    NSLog(@"hideOptionBar");
}

-(void)hiddenStatus
{
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        // iOS 7
        [self prefersStatusBarHidden];
        //        [self preferredStatusBarUpdateAnimation];
        [UIView animateWithDuration:0.5 animations:^{
            [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
        }];
    }

}

-(BOOL)prefersStatusBarHidden
{
    
    return isShowStatusBar;//隐藏为YES，显示为NO
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [titleLabel release];
    [mArticleWebView release];
    [topView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [titleLabel release];
    titleLabel = nil;
    [mArticleWebView release];
    mArticleWebView = nil;
    [topView release];
    topView = nil;
    [super viewDidUnload];
}
@end
